﻿using Autofac.Core;
using Consul;
using Microsoft.Extensions.Options;

namespace Demo.UserService.Registrys
{
    /// <summary>
    /// 服务注册类
    /// </summary>
    public class ConsulServiceRegistry
    {
        public ServiceRegistryOptions serviceRegistryOptions;

        public ConsulServiceRegistry(IOptions<ServiceRegistryOptions> options)
        {
            this.serviceRegistryOptions = options.Value;
        }

        /// <summary>
        /// 实现服务注册
        /// </summary>
        public void Registry()
        {
            // 1、创建consul服务器连接
            var consulClient = new ConsulClient(configuration =>
            {
                //1.1 填写consul服务地址
                configuration.Address = new Uri(serviceRegistryOptions.ConsulAddress);
            });

            // 2、创建服务地址
            var uri = new Uri(serviceRegistryOptions.ServiceAddress);

            // 3、注册服务地址
            // 3.1、准备 AgentServiceRegistration
            var registration = new AgentServiceRegistration()
            {
                ID = serviceRegistryOptions.ServiceID,
                Name = serviceRegistryOptions.ServiceName,
                Address = uri.Host, 
                Port = uri.Port,
                Tags = new string[] { },
                Check = new AgentServiceCheck  // 检测微服务是否正常
                {
                    // 3.1、consul健康检查超时间
                    Timeout = TimeSpan.FromSeconds(10),
                    // 3.2、服务停止5秒后注销服务
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                    // 3.3、consul健康检查地址
                    HTTP = serviceRegistryOptions.HealthCheckAddress,
                    // 3.4 consul健康检查间隔时间
                    Interval = TimeSpan.FromSeconds(10),
                }
            };

            // 3.2、注册服务地址
            consulClient.Agent.ServiceRegister(registration).Wait();

            // 4、服务注册成功
            Console.WriteLine($"微服务地址注册成功：{serviceRegistryOptions.ServiceAddress}");
        }

        /// <summary>
        /// 服务删除
        /// </summary>
        public void DeRegistry()
        {
            // 1、创建consul服务器连接
            var consulClient = new ConsulClient(configuration =>
            {
                //1.1 填写consul服务地址
                configuration.Address = new Uri("http://localhost:8500/");
            });
            //2、服务删除
            consulClient.Agent.ServiceDeregister(serviceRegistryOptions.ServiceID).Wait();

            //3、服务删除成功
            Console.WriteLine($"微服务地址删除成功：{serviceRegistryOptions.ServiceAddress}");
        }
    }
}
